package com.star.common.core.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 本地线程上下文：一个本地线程容器
 *
 * @author zhouhengzhe
 */
@Slf4j
public final class ThreadContext {
    private static final ThreadLocal<Map<String, Object>> LOCAL = new TransmittableThreadLocal();

    private ThreadContext() {
        log.info("### BASE INIT : ThreadContext ###");
    }

    public static <T> T get(String key) {
        Map<String, Object> map = LOCAL.get();
        return Objects.isNull(map) ? null : (T) map.get(key);
    }

    public static Map<String, Object> getValues() {
        Map<String, Object> map = LOCAL.get();
        return map;
    }

    public static <T> T getOrDefault(String key, T defaultValue) {
        Object o = get(key);
        if (o != null) {
            return (T) o;
        }
        return defaultValue;
    }

    public static void set(String key, Object value) {
        if (value == null) {
            return;
        }
        Map<String, Object> map = LOCAL.get();
        if (Objects.isNull(map)) {
            map = new ConcurrentHashMap<>(4);
        }
        map.put(key, value);
        LOCAL.set(map);
    }

    public static boolean contains(String key) {
        Map<String, Object> objects = LOCAL.get();
        if (objects == null) return false;
        return objects.containsKey(key);
    }

    public static void remove(String key) {
        Map<String, Object> objects = LOCAL.get();
        if (objects == null) {
            return;
        }
        objects.remove(key);
    }

    public static void clear() {
        LOCAL.remove();
    }
}
